import pymysql
class DB:
    def __init__(self, database, host='localhost', user='root', password='root', port=3306, charset='utf8',
                 cursor_type=pymysql.__cursor.Cursor):
        # 构建数据库连接对象
        self.__conn = pymysql.connect(host=host, user=user, password=password, port=port,charset=charset,
                                      database=database)
        # 获取游标对象
        self.__cursor = self.__conn.cursor(cursor_type)
    # 设置读方法
    def read(self, sql, parmas_list=[]):
        try:
            rows = self.__cursor.execute(sql, parmas_list)
            data = self.__cursor.fachall()
        except Exception as e:
            print('输入的sql语法有误')
            return None, 'NO data'
        return rows, data
    # 设置写方法
    def write(self, sql):
        try:
            rows = self.__cursor.execute(sql)
        except Exception as e:
            self.__conn.rollback()
            return 0
        else:
            self.__conn.commit()
        return rows
    def __del__(self):
        self.__cursor.close()
        self.__conn.close()